package com.cms.biz.category;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cms.bean.CategoryBean;
import com.cms.config.CategoryTypeDef;
import com.cms.database.DBHelper;
import com.cms.facade.RequestFacade;
import com.cms.framework.Command;
import com.cms.framework.CommandException;
import com.cms.framework.CommandToken;
import com.cms.util.ApplicationHelper;
import com.cms.util.StringHelper;

public class deleteCategoryCommand implements Command {

	String next;

	public deleteCategoryCommand(String next) {
		this.next = next;
	}

	@Override
	public String execute(HttpServletRequest req) throws CommandException {
		HttpSession session = req.getSession();
		Connection conn = DBHelper.getConn();
		PreparedStatement pst = null;
		String[] setIds = req.getParameterValues("setId");
		int categoryTypeId = StringHelper.isRequestParamEmptyInt(req, "categoryTypeId", CategoryTypeDef.NEW);

		if (!CommandToken.isValid(req)) {
			RequestFacade.setSuccessFlag(req, Boolean.FALSE);
			RequestFacade.setInvalidTokenMsg(req);
			return next;
		}
		
		if (setIds != null && setIds.length > 0) {

			try {
				pst = conn.prepareStatement(SQLString.DELETE_CATEGORY_BY_ID);
				for (int i = 0; i < setIds.length; i++) {
					System.out.println(".."+setIds[i]);
					pst.setInt(1, Integer.parseInt(setIds[i]));
					pst.addBatch();
				}
				pst.executeBatch();
				
	        	//synchronization
	        	List<CategoryBean> list = CategoryHelper.getCategoryListByTypeId(conn, categoryTypeId);
	        	ApplicationHelper.setApplicationSubCategoryListById(session, list, categoryTypeId);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (pst != null) {
					try {
						pst.close();
						pst = null;
					} catch (final SQLException e) {
					}
				}
				DBHelper.closeConn(conn);
			}
			
		}
		return next;
	}

}
